package com.zp.thread;
/**
 * 当访问某个对象的synchronized方法时，表示将该对象上锁；
 * 所以结果是先打印完hello，再打印完world；
 */
public class SynchronizedTest2 {
	public static void main(String[] args) {
		/**
		 * 一个对象：example
		 * synchronized关键字将该对象上锁，
		 * 并非该对象的一个方法；
		 */
		Example example = new Example();
		
		SynThread1 t1 = new SynThread1(example);
		SynThread2 t2 = new SynThread2(example);
		
		t1.start();
		t2.start();
	}
}

class Example{
	public synchronized void excute1(){
		for(int i=0;i<20;i++){
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("hello"+i);
		}
	}
	public synchronized void excute2(){
		for(int i=0;i<20;i++){
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("wrold"+i);
		}
	}
}

class SynThread1 extends Thread{
	
	private Example example;
	
	public SynThread1(Example example){
		this.example = example;
	}
	
	@Override
	public void run() {
		this.example.excute1();
	}
}

class SynThread2 extends Thread{
	
	private Example example;
	
	public SynThread2(Example example){
		this.example = example;
	}
	
	@Override
	public void run() {
		this.example.excute2();
	}
}


